//
//  WATFManager.swift
//  WiFiFaster
//
//  Created by one on 2023/12/28.
//

import UIKit
import CoreLocation
import Alamofire
import FirebaseRemoteConfig
import NetworkExtension

@objc protocol WATFManagerToolDelegate: NSObjectProtocol {
    @objc optional  func watf_downloadProcess(watf_value: String)
    @objc optional  func watf_downloadFinish(watf_value: String)
    @objc optional  func watf_uploadProcess(watf_value: String)
    @objc optional func watf_upLoadFinish(watf_value: String)
    @objc optional func watf_pingProcess(watf_ping: String)
    @objc optional func watf_pingFinish(watf_ping: String, watf_jitter: String, watf_loss: String)
    
}
let watf_ftvOne_key = "watf_ftvOne_key"
let watf_ftvTwo_key = "watf_ftvTwo_key"
class WATFManager: NSObject {
    @objc static let watf_manager = WATFManager()
    override init() {
        super.init()
        watf_ftvFireDone = true
        watf_creadteDefaultFTVModel()
        watf_addFTVStateChangeNoti()
        watf_netManager?.startListening(onUpdatePerforming: { quwf_state in
            if self.watf_netManager?.isReachable ?? false {
                switch quwf_state {
                case .notReachable:
                    WATFHudCom.watf_showMessage("The current network is unavailable, please check the network", isError: false)
                    break
                case .unknown:
                    
                    break
                case .reachable(.ethernetOrWiFi):
                    break
                    
                case .reachable(.cellular):
                    
                    break
                }
                
            } else {
                print("网络不可用")
            }
        })
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(self.watf_enterActive),
            name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(self.watf_enterBackground),
            name: UIApplication.didEnterBackgroundNotification, object: nil)
    }
    
    //MARK: - watf save key
    @objc func watf_saveIntKey(watf_key: String, watf_value: NSInteger, watf_timeID: String = "") {
        UserDefaults.standard.setValue(watf_value, forKey: watf_key+watf_timeID)
        UserDefaults.standard.synchronize()
    }
    @objc func watf_getIntValue(watf_key: String, watf_timeID: String = "") -> NSInteger {
        guard let watf_value =  UserDefaults.standard.value(forKey: watf_key+watf_timeID) as? NSInteger else { return 0 }
        return watf_value
    }
    
    @objc func watf_saveSrKey(watf_key: String, watf_value: String, watf_timeID: String = "") {
        UserDefaults.standard.setValue(watf_value, forKey: watf_key+watf_timeID)
        UserDefaults.standard.synchronize()
    }
    @objc func watf_getSrValue(watf_key: String, watf_timeID: String = "") -> String {
        guard let watf_value =  UserDefaults.standard.value(forKey: watf_key+watf_timeID) as? String else { return "" }
        return watf_value
    }
    //MARK: - watf net
    func watf_isCanNetWork() -> Bool {
        return watf_netManager?.status != .notReachable
    }
    //MARK: - watf lazy
    var watf_pingServe: WATFPingSer?
    var watf_pingErr = false
    var watf_stopDownloadRequest = false
    var watf_stopUploadRequest = false
    var watf_downloadRequest:DownloadRequest?
    var watf_uploadRequest:UploadRequest?
    var watf_downAddNumber = 0
    var watf_downloadName: String = "watf_downloadName"
    var watf_uploadAddNumber = 0
    var watf_uploadName: String = "watf_uploadName"
    var watf_downloadValue: Double = 0
    var watf_uploadValue: Double = 0
    var watf_speedType = 0
    weak var watf_delegate: WATFManagerToolDelegate?
    var watf_loctionManager = CLLocationManager()
    lazy var watf_timeID: String = {
        let watf_date = Date()
        let watf_calendar = Calendar.current
        let watf_year = watf_calendar.component(.year, from: watf_date)
        let watf_month = watf_calendar.component(.month, from: watf_date)
        let watf_day = watf_calendar.component(.day, from: watf_date)
        let watf_timeID = "\(watf_year)-\(watf_month)-\(watf_day)"
        return watf_timeID
    }()
    lazy var watf_funcModels: [WATFFuncModel] = {
        var watf_funcModels = [WATFFuncModel]()
        watf_funcModels.append(WATFFuncModel(watf_type: .watf_speed, watf_title: "Test Speed"))
        watf_funcModels.append(WATFFuncModel(watf_type: .watf_speedUP, watf_title: "Speed Up"))
        watf_funcModels.append(WATFFuncModel(watf_type: .watf_interference, watf_title: "Clear interference"))
        watf_funcModels.append(WATFFuncModel(watf_type: .watf_idle, watf_title: "Clear idle processes"))
        watf_funcModels.append(WATFFuncModel(watf_type: .watf_optimization, watf_title: "Optimization speed"))
        return watf_funcModels
    }()
    //MARK: - 1.0.1
    let watf_netManager = NetworkReachabilityManager()
    let watf_pingGroup1 = DispatchGroup()
    let watf_pingQueue1 = DispatchQueue(label: "com.wifiFaster.pingqueue1")
    let watf_pingGroup2 = DispatchGroup()
    let watf_pingQueue2 = DispatchQueue(label: "com.wifiFaster.pingqueue2")
    var watf_ftvModel1s = [WATFFTVTempModel]()
    var watf_ftvModels = [WATFFTVTempModel]()
    var watf_ftvChangeBlock: ((WATFFTVStateType)->())?
    var watf_ftvManager:NETunnelProviderManager?
    var watf_ftvStateClickType: WATFFTVStateClickType = .watf_none
    var watf_ftvCurStateType: WATFFTVStateType {
        return WATFFTVStateType(rawValue: watf_ftvManager?.connection.status.rawValue ?? 0) ?? .watf_disconnected
    }
    var watf_curFTVModel: WATFFTVTempModel?
    var watf_fireFTVModels = [WATFFTVTempModel]()
    var watf_ftvWork = false
    var watf_smartFTVModel: WATFFTVTempModel?
    var watf_defatulFTVModel: WATFFTVTempModel?
    var watf_ftv1Done = false
    var watf_ftv2Done = false
    var watf_ftvFireDone = false
    var watf_ftvRequest = false
    var watf_ftvAuth: Bool = false // 是否需要授权
    var watf_ftvListConfig = false
    var watf_fireconfig:RemoteConfig?
    var watf_testAdWork = false
    var watf_alertShow = false
    var watf_resultBack = false
    var watf_isFullAdView: Bool = false
  
    var watf_noLoading: Bool = false
    var watf_backTimeName: String = "watf_backTimeName"
    var watf_backTimeCount: NSInteger = 0
    var watf_launchView: WATFLaunchView?
    var watf_isAdClick: Bool = false
    var watf_isBack: Bool = false
    var watf_LaunchH: Bool = false
    var watf_backgroundTask: UIBackgroundTaskIdentifier = .invalid
   
}
let watf_appID = "6475335379"
extension WATFManager {
    func watf_switchAppStore()  {
        let watf_urlString = "itms-apps://itunes.apple.com/cn/app/id\(watf_appID)?mt=8&action=write-review"
        let url = URL(string: watf_urlString)
        if #available(iOS 10, *) {
            UIApplication.shared.open(url!, options: [:],
                                      completionHandler: {
                (success) in
            })
        } else {
            UIApplication.shared.openURL(url!)
        }
    }
    func watf_shareApp(watf_vc: WATFBaseViewController?) {
        var activityItems:[Any]?
        let url = URL(string: "https://itunes.apple.com/app/id\(watf_appID)")
        activityItems = ["WiFi Faster", url!]
        let watf_activity = UIActivityViewController(activityItems: activityItems!, applicationActivities: nil)
        watf_activity.excludedActivityTypes = [.saveToCameraRoll, .openInIBooks, .addToReadingList]
        watf_activity.completionWithItemsHandler = { a, c, r, e in
        }
        watf_vc?.present(watf_activity, animated: true)
    }
}
//MARK: - watf watf_enterBackground
extension WATFManager {
    func watf_registerBackgroundTask() {
        watf_backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
                // 当定时器任务完成后，结束后台任务
                self?.watf_endBackgroundTask()
            }
        }

        func watf_endBackgroundTask() {
            UIApplication.shared.endBackgroundTask(watf_backgroundTask)
            watf_backgroundTask = .invalid
        }
    @objc func watf_enterBackground() {
        watf_registerBackgroundTask()
        watf_isBack = true
       
       
         if watf_testAdWork {
            return
        }
        let watf_mainvc = WATFAppDelegate.watf_shared().watf_window?.rootViewController
        watf_mainvc?.view.endEditing(false)


//        if watf_isAdClick {
            WATFAppDelegate.watf_shared().watf_window?.rootViewController?.dismiss(animated: true)
//        }
        if watf_noLoading {
          
            return
        }
        watf_startTimerBack()
        
    }
    @objc func watf_enterActive() {
        watf_alertShow = true
        if (watf_ftvCurStateType == .watf_invalid || watf_ftvCurStateType == .watf_disconnected) {
            watf_ftvChangeBlock?(.watf_invalid)
        }
        if watf_testAdWork {
            watf_stopTimerBack()
            watf_isBack = false
            return
        }
        if watf_isAdClick {
//            watf_completion?(.watf_success)
            watf_isAdClick = false
            watf_noLoading = false

            watf_isBack = false
            watf_stopTimerBack()
            return
        }
        if watf_noLoading {
            watf_noLoading = false
            watf_stopTimerBack()

            watf_isBack = false
            return
        }
        if !watf_LaunchH {
            watf_stopTimerBack()
            watf_launchView?.watf_cancelLoading()
            watf_launchView?.watf_startLoading()

            watf_isBack = false
            return
        }
        if watf_backTimeCount >= 0 {
           
            if watf_launchView?.superview != nil {
                watf_launchView?.watf_cancelLoading()
                watf_launchView?.removeFromSuperview()
                //
            }
            watf_launchView = WATFLaunchView.watf_showView()
        }
        watf_stopTimerBack()

        watf_isBack = false
        
    }
    fileprivate func watf_startTimerBack() {
        watf_stopTimerBack()
        watf_backTimeName = WATFTimerCom.watf_timeTask(self, selector: #selector(watf_timeSumBack), start: 0, interval: 1, repeats: true, async: false, name: watf_backTimeName)
    }
    
    fileprivate func watf_stopTimerBack() {
        WATFTimerCom.watf_cancelTask(watf_backTimeName)
        watf_backTimeName = "watf_backTimeName"
        watf_backTimeCount = 0
        
    }
    
    @objc func watf_timeSumBack() {
        watf_backTimeCount = watf_backTimeCount + 1
        WATFPrintOpt(watf_cot: "[WATF]后台计时\(watf_backTimeCount)")
       
    }
}
